package com.hup.winHolderService.service;

import com.hup.utils.commons.DateBuilder;
import com.hup.utils.commons.hardware.HRobotJni;
import com.hup.utils.commons.start.SpringContext;
import com.hup.utils.commons.start.VersionConfig;
import com.hup.utils.commons.thread.ThreadUtil;
import com.hup.utils.io.batch.BatchUtil;
import com.hup.utils.io.batch.function.Shutdown;
import com.hup.winHolderService.config.ControllerExceptionHandler;
import com.hup.winHolderService.framework.exception.AppHiddenMsgException;
import com.hup.winHolderService.framework.exception.AppServerException;
import com.hup.winHolderService.framework.model.ExceptionResult.BaseResultException;
import com.hup.winHolderService.model.AppInfo;
import com.hup.winHolderService.model.AppInfo.SystemInfo;
import com.hup.winHolderService.model.ExternalAppConfig;
import com.hup.winHolderService.model.ExternalAppConfig.ExternalApp;
import com.hup.winHolderService.view.NotMutedFrame;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author hugan
 * @date 2020/3/2
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MainService {

    private final ScheduleService scheduleService;

    //状态管理 ===================
    public void exit() {
        ThreadUtil.start(() -> {
            //等待前端页面刷新
            log.info("1秒后退出程序");
            ThreadUtil.sleep(1000);
            System.exit(0);
        });
    }

    public AppInfo appInfo() {
        AppInfo res = new AppInfo();
        VersionConfig versionConfig = SpringContext.getBean(VersionConfig.class);
        res.version = versionConfig.version;
        res.buildTime = versionConfig.buildTime;
        res.systemInfo = new SystemInfo();
        res.systemInfo.isAcOnline = HRobotJni.isAcOnline();
        res.systemInfo.batteryValue = HRobotJni.getBatteryValue();
        res.systemInfo.mute = HRobotJni.isMute();
        res.systemInfo.volume = HRobotJni.getVolume();
        res.systemInfo.lockPlanTime = scheduleService.lockPlanTime();
        res.systemInfo.enableKillWinUpdateTask = scheduleService.isEnableKillWinUpdateTask();
        if (Shutdown.getLastShutdownTime() != null) {
            res.systemInfo.shutdownTime = DateBuilder.ymdHms(new Date(Shutdown.getLastShutdownTime()));
        }
        ExternalAppConfig externalAppConfig = SpringContext.getBean(ExternalAppConfig.class);
        res.lstExternalApp = externalAppConfig.getApps()
                .stream()
                .map(ExternalApp::getDesc)
                .collect(Collectors.toList());
        return res;
    }

    public void setMute(boolean isMute) {
        NotMutedFrame.setMute(isMute);
    }

    public void setVolume(int volume) {
        HRobotJni.setVolume(volume);
        NotMutedFrame.setMute(false);
    }

    public void muteAndLock() {
        HRobotJni.lockWorkStation();
        NotMutedFrame.setMute(true);
    }

    public void lock() {
        HRobotJni.lockWorkStation();
        //锁屏时,都刷新窗口状态:解决其他方式更新了静音状态
        NotMutedFrame.setMute(HRobotJni.isMute());
    }

    //电源管理 ===================
    private synchronized void cmdTask(String desc, Runnable task) {
        try {
            log.info("{}.st", desc);
            task.run();
        } catch (Throwable e) {
            BaseResultException resultException = ControllerExceptionHandler.getResultException(e, null);
            log.info("执行失败:{}", desc);
            resultException.doLog();
        }
    }

    public void sleep() {
        //或 rundll32.exe powrprof.dll,SetSuspendState 0,1,0
        cmdTask("睡眠", () -> BatchUtil.builder().exec("C:\\WINDOWS\\system32\\rundll32.exe powrprof.dll,SetSuspendState Sleep"));
    }

    public void shutdownCancel() {
        cmdTask("取消关机", () -> BatchUtil.builder().exec(Shutdown.cancel()));
    }

    public void shutdown(int minute) {
        cmdTask("计划关机", () -> {
            int time = minute * 60;
            BatchUtil.builder().exec(Shutdown.shutdown(time));
            log.info("将在{}关机", DateBuilder.ymdHms(new Date(Shutdown.getLastShutdownTime())));
        });
    }

    //外部程序
    public void runExternalApp(String name) {
        ExternalAppConfig config = SpringContext.getBean(ExternalAppConfig.class);
        //config = new ExternalAppConfig().loadFromFile();//test
        Optional<ExternalApp> optional = config.apps.stream()
                .filter(externalApp -> Objects.equals(externalApp.desc, name))
                .findFirst();
        if (!optional.isPresent()) throw new AppHiddenMsgException("配置中没有:" + name);

        try {
            ExternalApp externalApp = optional.get();
            HRobotJni.shellExecuteRun(externalApp.path, externalApp.param);
        } catch (Throwable e) {
            throw new AppServerException("[" + name + "]运行错误", e);
        }
    }

}
